package com.crazymakercircle.demo.zbl;

import com.crazymakercircle.util.Print;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantComunicatonTest {

    static Lock lock=new ReentrantLock();

    //获取一个显示锁绑定的Condition对象
    static private Condition condition = lock.newCondition();


    static  class WaitTarget implements  Runnable{

        @Override
        public void run() {
            lock.lock();
            try {
                Print.tcfo("等待方");
                condition.await();
                Print.tco("收到通知,等待方继续执行！！！");

            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                lock.unlock();
                Print.tcfo("等待方 释放锁结束！");
            }
        }
    }

    static  class  NotifyTarget implements  Runnable{

        @Override
        public void run() {
            lock.lock();
            try{
                Print.tcfo("我是通知方");
                condition.signal();
                Print.tcfo("发出通知 马上释放锁");
            }finally {
                lock.unlock();
                Print.tcfo("通知方 释放锁结束！");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(new WaitTarget(), "waitThread");

        thread.start();

        TimeUnit.SECONDS.sleep(2);

        Thread notifyThread = new Thread(new NotifyTarget(), "notifyThread");

        notifyThread.start();

        System.out.println(">>>>>>>>>>>> main end>>>>>>>>>>>>");
    }

}
